package com.hntx.joymusic.webscoket;

import android.text.TextUtils;
import android.util.Log;

import com.hntx.joymusic.MyApp;
import com.hntx.joymusic.bean.SocketBean;
import com.hntx.joymusic.bus.RxBus;
import com.hntx.joymusic.util.GsonUtils;
import com.hntx.joymusic.util.SetNetWorkUtils;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

public class WebScoketClient {
    private String TAG = "WebScoketClient";
        String url = "ws://47.102.125.184:8080/joymusic_cs_sxyd/websocket?userid=";
//    String url = "ws://111.19.171.172:8084/websocket/websocket?userid=";
    private String serverHostName = null;
    public static WebScoketClient webScoketClient;
    private static WebSocketClient mJavaWebSocketClient;
    private boolean isJavaConnect = false;
    public static boolean isConnecting = true;

    public WebScoketClient() {
        super();
    }

    public static WebScoketClient getWebScoketClient() {
        if (webScoketClient == null) {
            synchronized (WebScoketClient.class) {
                if (webScoketClient == null) {
                    webScoketClient = new WebScoketClient();
                }
            }
        }
        return webScoketClient;
    }

    public static WebSocketClient getJavaWebSocket() {
        if (mJavaWebSocketClient != null) {
            return mJavaWebSocketClient;
        }
        return null;
    }

    public WebScoketConnectListener webScoketConnectListener;

    public interface WebScoketConnectListener {
        void JavaWebSocketOpen(WebSocketClient mJavaWebSocketClient);

        void JavaWebsocketClosed(int code, String reason, boolean remote);

        void JavaWebSocketError(Exception ex);
    }

    public void addWebScoketConnectListener(WebScoketConnectListener webScoketConnectListener) {
        this.webScoketConnectListener = webScoketConnectListener;
    }

    private SocketBean parseJsonToMap(final String json) {
        SocketBean socketBean = GsonUtils.getGson().fromJson(json, SocketBean.class);
        return socketBean;
    }

    public void sendBack(Map<String, String> map) {
//        if (serverHostName == null) {
//            serverHostName = getMerchId(R.string.merchant_id);
//        }
        sendPush(serverHostName, map);
    }

    private void sendPush(String serverHostName, Map<String, String> pushMap) {
        if (TextUtils.isEmpty(serverHostName)) {
        }
//        JsonBean jb = new JsonBean();
//        jb.setMsgType("0");
//        if (!TextUtils.isEmpty(userId)) {
//            jb.setUserId(userId);
//        }
//        jb.setTargetId(serverHostName);
//        jb.setContent(pushMap);
//        String params = GsonUtils.getGson().toJson(jb);
        String params = "";
        if (TextUtils.isEmpty(params)) {
            return;
        }
        /*检查网络*/
        if (!SetNetWorkUtils.getInstance(MyApp.getInstance())
                .isNetworkAvailable(MyApp.getInstance())) {
            return;
        }
        if (isJavaConnect) {
            try {
                mJavaWebSocketClient.send(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMsg(String msg) {
        if (isJavaConnect) {
            try {
                mJavaWebSocketClient.send(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public void javaWebSocketLogin(String username) {
        URI uri = null;
//        String username = "123456";
        if (username != null) {
            String newUrl = url + username;
            try {
                uri = new URI(newUrl);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
            mJavaWebSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    isJavaConnect = true;
                    isConnecting = false;
                    if (webScoketConnectListener != null) {
                        webScoketConnectListener.JavaWebSocketOpen(mJavaWebSocketClient);
                    }
                }

                @Override
                public void onMessage(String message) {
                    Log.d(TAG, "服务器消息：" + message);
                    String action = null;
                    try {
                        JSONObject jsonObject = new JSONObject(message);
                        action = jsonObject.get("action").toString();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                    SocketBean bean = parseJsonToMap(message);
                    if (TextUtils.isEmpty(action)) {
                        return;
                    }
                    if (action.equals("order") ||
                            action.equals("list") ||
                            action.equals("delete")) {
                        SocketBean bean = parseJsonToMap(message);
                        Log.d(TAG, "服务器消息111：" + bean.toString());
//                    LiveDataBus.getInstance().send("socketmsg", bean);
                        RxBus.getInstance().send(bean);
                    } else {
                        Log.d(TAG, "服务器消息222：" + action);
                        RxBus.getInstance("playmsg").send(action);
                    }
                }

                @Override
                public void onClose(int code, String reason, boolean remote) {
                    isJavaConnect = false;
                    isConnecting = true;
                    if (webScoketConnectListener != null) {
                        webScoketConnectListener.JavaWebsocketClosed(code, reason, remote);
                    }
                }

                @Override
                public void onError(Exception ex) {
                    isJavaConnect = false;
                    isConnecting = true;
                    if (webScoketConnectListener != null) {
                        webScoketConnectListener.JavaWebSocketError(ex);
                    }
                }
            };
        }
    }

    public void javaWebSocketConnect(String username) {
        if (TextUtils.isEmpty(username)) return;
        javaWebSocketLogin(username);
        mJavaWebSocketClient.connect();
    }

    public void javaWebSocketReconnect() {
        if (isConnecting) {
            isConnecting = false;
            if (mJavaWebSocketClient != null) {
                mJavaWebSocketClient.reconnect();
            }
        }
    }
}
